// src/main/java/dhee/wtqshopproject/utils/CategoryMapperUtils.java
package dhee.wtqshopproject.utils;

import dhee.wtqshopproject.dao.CategoryMapper;
import dhee.wtqshopproject.entity.Category;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

@Component
public class CategoryMapperUtils {

    private static CategoryMapperUtils instance;

    @Resource
    private CategoryMapper categoryMapper;

    @PostConstruct
    public void init() {
        instance = this;
        instance.categoryMapper = this.categoryMapper;
    }

    // 新增分类
    public static int insertCategory(Category category) {
        return instance.categoryMapper.insert(category);
    }

    // 修改后的删除方法
    public static boolean deleteCategory(Integer categoryId) {
        try {
            return instance.categoryMapper.deleteById(categoryId) > 0;
        } catch (DataIntegrityViolationException e) {
            throw new RuntimeException("该分类下存在关联商品，无法删除，建议使用停用方法");

        }
        // 数据库处理 停用部分isuse=0 数据库存在 后台设置状态停用 前端数据不会返回
//            // 获取关联商品信息 未完成部分
//            List<Product> relatedProducts = instance.productMapper.selectByCategoryId(categoryId);
//            // 构建商品信息字符串
//            String productList = relatedProducts.stream()
//                    .map(p -> "商品ID：" + p.getProductId() + " 名称：" + p.getProductName())
//                    .collect(Collectors.joining("\n"));
//            throw new RuntimeException(String.format(
//                    "分类ID：%d 下存在 %d 个关联商品，无法删除。\n关联商品列表：\n%s\n建议使用停用功能",
//                    categoryId, relatedProducts.size(), productList
//            ));
//        }
    }
    // 修改分类
    public static boolean updateCategory(Category category) {
        return instance.categoryMapper.update(category) > 0;
    }

    // 查询所有分类
    public static List<Category> selectAllCategories() {
        return instance.categoryMapper.selectAll();
    }

    // 按ID查询分类
    public static Category selectCategoryById(Integer categoryId) {
        return instance.categoryMapper.selectById(categoryId);
    }
}